package com.Flucard_IT;

import utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import controller.CheckFlucardAsync;
import controller.ConnectToServerAsync;
import controller.GetDataFromServerAsync;
import define.Constants;

public class SplashScreen extends Activity {
	/**
	 * String section
	 */
	public static boolean IS_DISABLE_HANDLER = false;
	public static boolean IS_ENTER_CHECK_CONNECTION_HANDLER = false;
	public static boolean IS_FIRST_TIME = true;

	public static String SSID = "";

	private final static String TAG = SplashScreen.class.getSimpleName();

	/**
	 * Data section
	 */

	/**
	 * Interface section
	 */
	private Runnable mRunnableOpenApp = new Runnable() {
		@Override
		public void run() {
			/**
			 * Check wireless connection
			 */
			if (mCmConnectionManager.getNetworkInfo(
					ConnectivityManager.TYPE_WIFI).isConnected()) {
				mWiWifiInfo = mWmWifiManager.getConnectionInfo();
				SSID = mWiWifiInfo.getSSID().replace("\"", "");
			}

			if (IS_ENTER_CHECK_CONNECTION_HANDLER) {
				new CheckFlucardAsync(SplashScreen.this).execute();
			}

			/**
			 * Disable handler when already connected to card
			 */
			if (!IS_DISABLE_HANDLER) {
				mHandlerCheckConnection.postDelayed(this,
						Constants.HANDLER_OPEN_APP_DELAY);
			}
		}
	};

	/**
	 * Handler section
	 */
	private Handler mHandlerCheckConnection = new Handler();
	private static Handler mHandlerFailedConnection = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Constants.utils.hideProgressDialog();

			if (!IS_DISABLE_HANDLER) {
				mAdFailedConnection.show();
			}
		}
	};

	/**
	 * Shared Preference section
	 */

	/**
	 * Thread section
	 */
	// Check for Wireless connection and auto connect to Card
	private Thread mThreadCheckWirelessConnection = new Thread() {
		@Override
		public void run() {
			/**
			 * Check wireless connection
			 */
			if (mCmConnectionManager.getNetworkInfo(
					ConnectivityManager.TYPE_WIFI).isConnected()) {
				mWiWifiInfo = mWmWifiManager.getConnectionInfo();
				SSID = mWiWifiInfo.getSSID().replace("\"", "");
			}

			/**
			 * Check SSID same as "Trek_FLUCARD_Wifi" or not
			 */
			checkSSIDInWirelessSetting();
		}
	};;

	/**
	 * View section
	 */
	public static AlertDialog.Builder mAdFailedConnection;

	/**
	 * The others section
	 */
	public static Context mContext;
	private ConnectivityManager mCmConnectionManager;
	private WifiManager mWmWifiManager;
	private WifiInfo mWiWifiInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_splash_screen);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		mContext = this;
		Constants.utils = new Utils(this);

		/**
		 * Get data from server
		 */
		new GetDataFromServerAsync().execute();

		// Initialize value
		initialDialog();

		// Initiate variables
		initialVariables();

		/**
		 * Start the thread to check wireless connection
		 */
		mThreadCheckWirelessConnection.start();

		/**
		 * Start Handler to open the application, in case disconnected wireless
		 * and connect again
		 */
		mHandlerCheckConnection.post(mRunnableOpenApp);
	}

	@Override
	protected void onResume() {
		super.onResume();

		/**
		 * Check already connected to the Card or not
		 */
		new ConnectToServerAsync(this).execute();
	}

	/**
	 * Initialize methods
	 */

	private void initialDialog() {
		mAdFailedConnection = new AlertDialog.Builder(this)
				.setCancelable(false)
				.setTitle(getString(R.string.error))
				.setIcon(R.drawable.ibtn_error_dismiss)
				.setMessage(getString(R.string.ensure_connect_flucard_wifi))
				.setPositiveButton(getString(R.string.ok),
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface d,
									int whichButton) {
								/**
								 * Enter Check connection Handler
								 */
								IS_ENTER_CHECK_CONNECTION_HANDLER = true;

								// Transfer to Wireless Settings System
								finish();
								startActivity(new Intent(
										Settings.ACTION_WIFI_SETTINGS));
							}
						});
	}

	private void initialVariables() {
		mCmConnectionManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		mWmWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
	}

	/**
	 * Basic methods
	 */

	private void checkSSIDInWirelessSetting() {
		/**
		 * Check current SSID is correct or not
		 */
		if (SSID != null & !SSID.equals("")
				& ConnectToServerAsync.IS_CONNECT_TO_CARD) {
			/**
			 * If used correct wireless
			 */
			transferToHomePage();
		} else {
			/**
			 * If used wrong wireless
			 */
			/**
			 * Can not get data from server, error happened
			 */
			mHandlerFailedConnection.sendMessage(mHandlerFailedConnection
					.obtainMessage());
		}
	}

	private void transferToHomePage() {
		/**
		 * If can get, transfer to new page
		 */
		finish();

		/**
		 * If used correct wireless name, transfer to this page
		 */
		startActivity(new Intent(SplashScreen.this, Home.class));
	}
}
